package gaml.text.parser;

import gaml.error.GamlException;
import gaml.text.YamlText;
import gaml.text.YamlTextParser;
import gaml.yaml.AliasNode;
import gaml.yaml.YamlNode;
import gaml.yaml.ahchor.YamlAnchorCodeStore;

/**
 * get node alias from it's text representation
 * @author shnireck
 *
 */
public class AliasNodeParser implements YamlTextParser {
	static final String incorrectAliasNodeFormat = "Mailformed alias node [%s] (line num %d)";
	
	YamlAnchorCodeStore anchors = null;
	
	public AliasNodeParser (YamlAnchorCodeStore anchors) { this.anchors = anchors; }
	
	@Override
	public boolean isParserFor (YamlText text) throws GamlException { return text.getValue ().startsWith ("*"); }
	
	@Override
	public String getParsingTail (YamlText text) throws GamlException { return text.getValue ().substring (1).trim (); }

	@Override
	public YamlNode parseText (YamlText text, YamlNode parent) throws GamlException {
		if (! isParserFor (text)) throw new GamlException (String.format (incorrectAliasNodeFormat, text.getValue (), text.getCurrent ()));
		
		YamlNode node = new AliasNode (parent, anchors.getAnchor (getParsingTail (text)));
		text.next ();

		return node;
	}
}